<template>
  <div style="padding: 20px;"
       class="checkResultNoClass">
    <el-form :inline="true"
             :model="queryForm"
             class="demo-form-inline">
      <el-form-item label="检查对象">
        <el-input clearable
                  v-model="queryForm.obj_no"
                  placeholder="请输入检查对象"></el-input>
      </el-form-item>
      <el-form-item label="检查模块名称">
        <el-input clearable
                  v-model="queryForm.module_name"
                  placeholder="请输入检查模块名称"></el-input>
      </el-form-item>
      <el-form-item label="检查项名称">
        <el-input clearable
                  v-model="queryForm.check_item_name"
                  placeholder="请输入检查项名称"></el-input>
      </el-form-item>
      <el-form-item label="记录人">
        <el-input clearable
                  v-model="queryForm.created_by_name"
                  placeholder="请输入记录人"></el-input>
      </el-form-item>

      <el-form-item label="日期">
        <el-date-picker type="daterange"
                        v-model="queryForm.selectTime"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        :style="{ width: '100%' }"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        clearable>
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button @click="_searchTable"
                   type="primary">查询</el-button>
        <el-button @click="_resetForm">重置</el-button>
        <el-button @click="handleExport"
                   type="primary">批量导出</el-button>
        <!--        :loading="downloadLoading"-->
      </el-form-item>
    </el-form>

    <el-table :data="tableData"
              ref="multipleTable"
              @selection-change="handleSelectionChange"
              fit
              highlight-current-row
              height="65vh"
              style="width: 100%;overflow: auto;">
      <el-table-column type="selection"
                       width="55">
      </el-table-column>
      <el-table-column width="60"
                       label="序号">
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="检查对象"
                       prop="obj_no"></el-table-column>
      <el-table-column label="检查模块名称"
                       prop="module_name"></el-table-column>
      <el-table-column label="检查项名称"
                       prop="check_item_name"></el-table-column>
      <el-table-column label="记录人"
                       prop="created_by_name"></el-table-column>
      <el-table-column label="记录时间"
                       prop="created_at"></el-table-column>

      <el-table-column label="操作"
                       width="200"
                       fixed="right">
        <template slot-scope="scope">
          <el-button @click="_handleOperate(scope.row, 'detail')"
                     type="text">
            详情
          </el-button>
          <el-button @click="_handleOperate(scope.row, 'print')"
                     type="text">
            打印
          </el-button>
          <el-button @click="_handleOperate(scope.row, 'qrcode')"
                     type="text">
            二维码
          </el-button>
          <el-button @click="_handleOperate(scope.row, 'delete')"
                     type="text">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="display: flex;justify-content: center;"
                   background
                   :current-page="queryForm.page"
                   :page-sizes="[10, 20, 50, 100]"
                   :page-size="queryForm.page_size"
                   :total="queryForm.total_count"
                   layout="total, sizes, prev, pager, next, jumper"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"></el-pagination>

    <el-dialog title="详情"
               :width="'40%'"
               top="50px"
               :visible.sync="detailDialogFlag">

      <div style="max-height: 600px;overflow: auto;">
        <div style="display: flex;justify-content: center;"
             v-if="dialogType=='qrcode'">
          <div id="qrcode"
               ref="qrcode"></div>

        </div>

        <div ref="print"
             id="print"
             v-else>

          <el-row style="font-size: 18px;">
            <el-col :span="24">
              记录对象：
              <p class="textBackground">{{detailInfo.obj_no}}</p>
            </el-col>

            <el-col :span="24"
                    v-for="(item,idx) in detailInfo.content_detail"
                    :key="idx">
              <div style="vertical-align: top;">{{item.content_name}}：</div>

              <!--            文本-->
              <p v-if="item.control_type==1||item.control_type==2"
                 class="textBackground">{{item.real_value[0].value||''}}</p>

              <!--            合格不合格-->
              <div v-if="item.control_type==6"
                   class="textBackground">
                <p v-if="item.real_value[0].value==='0'">不合格</p>
                <p v-if="item.real_value[0].value==='1'">合格</p>
              </div>
              <!--            图片-->
              <div v-if="item.control_type==7">

                <el-image v-if="k"
                          v-for="(k,idx) in item.real_value"
                          :key="idx"
                          fit="cover"
                          style="width: 120px;height: 120px;margin-right: 10px;"
                          :preview-src-list="item.real_value"
                          :src="k">
                </el-image>

                <span v-else>暂无图片</span>
              </div>

              <!--            单选下拉框-->
              <div v-if="item.control_type==3"
                   class="textBackground">
                <p v-if="item.real_value[0]!==''">{{item.real_value[0]}}</p>
                <p v-else>暂无选项</p>
                <!--                <el-select v-model="item.real_value[0]"-->
                <!--                           size="mini" disabled>-->
                <!--                  <el-option v-for="k in item.origin_data"-->
                <!--                             :label="k.key"-->
                <!--                             :value="k.val"-->
                <!--                             :key="k.val"></el-option>-->
                <!--                </el-select>-->
              </div>
              <!--            多选下拉框-->
              <div v-if="item.control_type==15"
                   class="textBackground">
                <p v-if="item.real_value[0]!==''">{{item.real_value[0]}}</p>
                <p v-else>暂无选项</p>
                <!--                <el-select v-model="item.real_value[0].split(',')"-->
                <!--                           multiple-->
                <!--                           disabled-->
                <!--                           size="mini" >-->
                <!--                  <el-option v-for="k in item.origin_data"-->
                <!--                             :label="k.key"-->
                <!--                             :value="k.val"-->
                <!--                             :key="k.val"></el-option>-->
                <!--                </el-select>-->
              </div>

              <div v-if="item.control_type==12"
                   class="textBackground">
                <el-row>
                  <el-col :span="4">姓名:</el-col>
                  <el-col :span="20">
                    <p>{{item.real_value[0].name}}</p>
                  </el-col>
                  <el-col :span="4">公司:</el-col>
                  <el-col :span="20">
                    <p>{{item.real_value[0].company}}</p>
                  </el-col>

                  <el-col :span="4">手机号:</el-col>
                  <el-col :span="20">
                    <p>{{item.real_value[0].phone}}</p>
                  </el-col>
                </el-row>

              </div>

            </el-col>
          </el-row>

        </div>
      </div>

      <div slot="footer"
           class="dialog-footer">
        <el-button @click="detailDialogFlag = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// import {DeviceManageAPI} from "../../services/DeviceManage";
// import {CommonManageAPI} from "../../services/CommonManage";
import QRCode from 'qrcodejs2' // 引入qrcode
import { CommonCheckApi } from '@/services/SystemSetting'

export default {
  name: "deviceList",

  data () {
    return {

      detailDialogFlag: false,
      dialogType: '',
      detailInfo: {},
      selectRowData: {},
      queryForm: {
        project_id: '',
        // project_id: 358,
        selectTime: undefined,
        page: 1,
        page_size: 10,
        total_count: 0,
      },
      downloadLoading: false,
      tableData: [],

      multipleSelection: [],
      idList: [],
    };
  },
  mounted () {
    let routeProId = this.$route.query.project_id || '';//项目主键值
    this.queryForm.project_id = routeProId ? routeProId : this.$store.state.choosedProject.project_id
    this._getList()
  },
  watch: {
    '$store.state.choosedProject.project_id': function (val) {
      let routeProId = this.$route.query.project_id || '';//项目主键值
      this.queryForm.project_id = routeProId ? routeProId : val;
      this._getList()
    }
  },
  methods: {

    printContext () {
      setTimeout(() => {
        this.$print(this.$refs.print)
      }, 2000)
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
      this.idList = []
      this.multipleSelection.forEach(v => {
        this.idList.push(v._id)
      })
      console.warn(this.idList)
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.queryForm.page_size = val
      this._getList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.queryForm.page = val
      this._getList()
    },

    _getList () {
      this.queryForm.start_time = this.queryForm.selectTime ? this.queryForm.selectTime[0] : ''
      this.queryForm.end_time = this.queryForm.selectTime ? this.queryForm.selectTime[1] : ''

      if (!this.queryForm.project_id) return

      CommonCheckApi.getCheckResultNoListAPI({
        params: this.queryForm
      }).then(res => {
        console.warn(res)
        let data = res.data
        this.tableData = data.list
        this.queryForm.page = data.page
        this.queryForm.page_size = data.page_size
        this.queryForm.total_count = data.total_count
      })
    },
    _getDetail () {

      CommonCheckApi.getCheckResultNoDetailAPI({
        params: {
          id: this.selectRowData._id || ''
        }
      }).then(res => {

        this.detailInfo = res.data

        this.detailInfo.content_detail.forEach(item => {


          if (item.control_type == 3 || item.control_type == 15) {
            item.real_value = item.real_value || ['']
          } else {
            item.real_value = item.real_value || [{ value: '' }]
          }

        })

        console.warn('detailInfo', this.detailInfo)

        if (this.dialogType == 'print') {
          this.$nextTick(() => {
            this.printContext()
          })
        }
      })

    },
    _searchTable () {
      this.queryForm.page = 1;
      this._getList();
    },

    _handleOperate (row, type) {
      // console.warn(localStorage.getItem('AllProjectList'))
      this.selectRowData = { ...row }
      this.dialogType = type
      if (type == 'detail') {
        this.detailDialogFlag = true
        this._getDetail()
      }
      if (type == 'print') {
        this.detailDialogFlag = true
        this._getDetail()
      }
      if (type == 'qrcode') {

        this.detailDialogFlag = true
        this.$nextTick(() => {
          document.getElementById('qrcode').innerHTML = ''
          let qrcode = new QRCode('qrcode', {
            width: 132,
            height: 132,
            text: `${process.env.URL_ROOT}/checkResultDetail?id=${row._id}`, // 二维码地址
            colorDark: "#000",
            colorLight: "#fff",
          })
        })
      }
      if (type == 'delete') {
        this.$confirm("是否删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            CommonCheckApi.deleteCheckResultAPI({
              params: {
                id: row._id
              }
            }).then(res => {
              if (res.code === 0) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this._getList()
              } else {
                this.$message.error(res.msg)
              }
            })
          })
      }
    },
    _resetForm () {
      this.queryForm = this.$options.data().queryForm;
      let routeProId = this.$route.query.project_id || '';//项目主键值
      this.queryForm.project_id = routeProId ? routeProId : this.$store.state.choosedProject.project_id
      this._searchTable();
    },
    handleExport () {
      if (this.multipleSelection.length) {
        this.downloadLoading = true
        import('@/plugs/Export2Excel').then(excel => {
          const tHeader = ['检查对象', '检查模块名称', '检查项名称', '记录人', '记录时间']
          const filterVal = ['obj_no', 'module_name', 'check_item_name', 'created_by_name', 'created_at']
          const list = this.multipleSelection
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '检查记录表'
          })
          this.$refs.multipleTable.clearSelection()
          this.downloadLoading = false
        })
        let url = `${process.env.API_ROOT}/web/v1/common_check/check_item/export?id=${this.idList.join()}`
        console.warn(url)
        window.open(url)

      } else {
        this.$message({
          message: '请至少选择一项',
          type: 'warning'
        })
      }
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  },
};
</script>

<style scoped lang="scss">
.el-pagination {
  margin-top: 20px;
}

.textBackground {
  padding: 10px;
  background: #f7f7f7;
}
.checkResultNoClass {
  .el-image {
    /deep/ .el-icon-circle-close {
      font-size: 50px;
      color: white;
    }
  }
}
</style>
